//
//  AppDelegate.m
//  WanTao
//
//  Created by Macbook Pro on 2019/3/13.
//  Copyright © 2019 Macbook Pro. All rights reserved.
//

#import "AppDelegate.h"
#import "FKNavVC.h"
#import "FKLoginVC.h"
#import <IQKeyboardManager.h>

#import <UMCommon/UMCommon.h>
#import <UMShare/UMShare.h>
#import <WXApi.h> // 微信支付
#import <AlipaySDK/AlipaySDK.h>

@interface AppDelegate ()<WXApiDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.rootViewController = [[NSClassFromString(@"FKTabBarVC") alloc] init];
    [self.window makeKeyAndVisible];
    
    IQKeyboardManager *keyboardManager = [IQKeyboardManager sharedManager]; // 获取类库的单例变量
    keyboardManager.enable = YES; // 控制整个功能是否启用
    keyboardManager.shouldResignOnTouchOutside = YES; // 控制点击背景是否收起键盘
    
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD setMaximumDismissTimeInterval:0.5];
    
    // 注册友盟
    [WXApi registerApp:AppID_WX];
    [self registerUMKey:launchOptions];
    return YES;
}

#pragma mark -  友盟分享
/** 注册平台 */
- (void)registerUMKey:(NSDictionary *)launchOptions
{
    //开发者需要显式的调用此函数，日志系统才能工作
        [UMConfigure setLogEnabled:YES];
    [UMConfigure initWithAppkey:AppKey_UMCShare channel:nil];
    [UMSocialGlobal shareInstance].isUsingWaterMark = false;
    
    [[UMSocialManager defaultManager] openLog:true];
    /* 微信 */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:AppID_WX appSecret:AppSecret_WX redirectURL:nil];
    /* QQ */
//    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:AppID_QQ  appSecret:AppKey_QQ redirectURL:nil];
    
    [[UMSocialManager defaultManager] removePlatformProviderWithPlatformTypes:@[@(UMSocialPlatformType_WechatFavorite)]];
}

#pragma mark - 配置友盟回调
// 支持所有iOS系统
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            [self alipayHandler:resultDic];
        }];
    } else if ([sourceApplication isEqualToString:@"com.tencent.xin"]) { // 微信支付
        [WXApi handleOpenURL:url delegate:self];
    }
    return result;
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
    BOOL result = [[UMSocialManager defaultManager]  handleOpenURL:url options:options];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    if ([url.host isEqualToString:@"safepay"]) { // 支付宝
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            [self alipayHandler:resultDic];
        }];
    } else if (@available(iOS 9.0, *)) {
        if ([options[UIApplicationOpenURLOptionsSourceApplicationKey] isEqualToString:@"com.tencent.xin"]) { // 微信支付
            [WXApi handleOpenURL:url delegate:self];
        }
    } else {
        // Fallback on earlier versions
    }
    
    return result;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}

#pragma mark - 处理支付宝支付回调
- (void)alipayHandler:(NSDictionary *)dict
{
    BOOL success = false;
    if ([dict[@"resultStatus"] isEqualToString:@"9000"]) {
        success = true;
        [SVProgressHUD showSuccessWithStatus:@"支付成功！"];
    } else if ([dict[@"resultStatus"] isEqualToString:@"6001"]){
        [SVProgressHUD showInfoWithStatus:@"取消支付！"];
    } else if ([dict[@"resultStatus"] isEqualToString:@"4000"]){
        [SVProgressHUD showInfoWithStatus:@"支付失败！"];
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"alipay" object:nil userInfo:@{@"success" : @(success)}];
}

#pragma mark -  微信请求后的返回的回调
-(void)onResp:(BaseResp*)resp
{
    if ([resp isKindOfClass:[PayResp class]]) {
        PayResp *response = (PayResp*)resp;
        
        BOOL success = false;
        switch (response.errCode) {
            case WXSuccess:
                success = true;
                [SVProgressHUD showSuccessWithStatus:@"支付成功"];
                break;
            case WXErrCodeUserCancel:
                [SVProgressHUD showInfoWithStatus:@"支付取消"];
                break;
            default:
                [SVProgressHUD showInfoWithStatus:@"支付失败"];
                break;
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"wechatPay" object:nil userInfo:@{@"success" : @(success)}];
    } else if ([resp isKindOfClass:[SendAuthResp class]]) { // 登录授权回调
        
    }
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
